package com.zsc.common.web.interceptor;

import com.alibaba.fastjson.TypeReference;
import com.tbdp.common.model.User;
import com.zsc.common.web.handler.UserAuthServiceHandler;
import com.zsc.common.web.result.Result;
import com.zsc.common.web.util.CodeEnum;
import com.zsc.common.web.util.JsonUtils;
import com.zsc.common.web.util.Constant;
import com.zsc.common.web.util.ResponseUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.zsc.common.web.util.ResponseUtils.fail;

/**
 * UserAuthServiceHandler.java是互动平台的用户认证授权业务处理拦截类，过滤没有登录的用户。
 *
 * @author jason
 * @version 1.0 2017年3月16日
 */
public class UserLoginInterceptor extends HandlerInterceptorAdapter {

    /**
     * 日志器
     */
    private static final Logger logger = LoggerFactory.getLogger(UserLoginInterceptor.class);

    /**
     * 用户认证授权业务处理器
     */
    @Autowired
    private UserAuthServiceHandler serviceHandler;

    /**
     * 在Session里缓存当前登录用户信息有效分钟数
     */
    @Value(value = "${commons.user.session.expire.minute}")
    private int userSessionExpireMinute;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        String userToken = request.getParameter("token");
        if (logger.isDebugEnabled()) {
            logger.debug("request url {} token {}", uri, userToken);
        }
        if (StringUtils.isEmpty(userToken)) {
            ResponseUtils.fail(response, CodeEnum.code990502);
            return false;
        }
        // 检查用户session是否为空
        User user = (User) request.getSession().getAttribute(Constant.KEY_LOGIN_USER);
        if (user != null && user.getExpireTime() > System.currentTimeMillis()) {
            logger.debug("find message {} in seesion token ", user.getUserId(), userToken);
            return true;
        }

        // 向用户认证中心认证当前登录用户，并且获取他的信息
        serviceHandler.setToken(userToken);
        serviceHandler.service();
        if (serviceHandler.isSuccess()) {
            Result<User> result = JsonUtils.fromJson(serviceHandler.getResponseData(), new TypeReference<Result<User>>() {
            });
            if (result == null) {
                ResponseUtils.fail(response, CodeEnum.code990006);
                return false;
            } else {
                if (result.getCode() == CodeEnum.code8200.getCode()) {
                    user = result.getResult();
                    user.setExpireTime(System.currentTimeMillis() + userSessionExpireMinute * 60000);
                    request.getSession(true).setAttribute(Constant.KEY_LOGIN_USER, user);
                } else {
                    ResponseUtils.fail(response, result.getCode(), result.getMsg());
                    return false;
                }
            }
        } else {
            ResponseUtils.fail(response, CodeEnum.code990502);
            return false;
        }

        return true;
    }
}
